﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Collections;
using Web.SystemConfig.Services;
using System.Data;
using Microsoft.Practices.Unity;
using ePlanet.ArchiveMange.Services;
using ePlanet.ArchiveMange.Models;
using DreamBuilder.Core.Message;
using DreamBuilder.Core.Container;
using Web.SystemConfig.WorkFlow;
using Web.SystemConfig.SysCache;

namespace Web.Views.ArchiveFlowView
{
    public partial class CDArchiveView : ArchiveFlowEditPageBase
    {
        #region 属性变量
        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }

        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }


        [Dependency]
        public IAuth_Org orgService
        {
            get;
            set;
        }

        public string archiveTypeName;


        /// <summary>
        /// 档案类型
        /// </summary>
        public string ReqArchiveType
        {
            get
            {
                if (this.Request.QueryString["archiveType"] != null)
                {
                    return this.Request.QueryString["archiveType"];
                }
                else
                {
                    throw new Exception("档案类型不能为空");
                }
            }
        }
        #endregion
        #region 页面初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            this.CurrentPageState = PageState.State_Edit;
            if (!IsPostBack)
            {
                ICDArchiveService cdService = UContainer.Resolve<ICDArchiveService>();
                ArchiveMangeModal.CD_ARCHIVEDataTable documentArchiveTable = cdService.GetAllDocumenArchivetDataById(ArchiveID);
                if (documentArchiveTable != null && documentArchiveTable.Rows.Count > 0)
                {
                    ArchiveMangeModal.CD_ARCHIVERow row = documentArchiveTable.Rows[0] as ArchiveMangeModal.CD_ARCHIVERow;
                    GetPrivilege(CurrentArchiveKind, row.DATAID, row.STATUSID.ToString());

                }
                else
                {
                    Alert("未找到相应数据！");
                    GoBack();
                }
                if (!canView)
                {
                    Alert("您无权查看该数据！");
                    GoBack();
                }
                if (!canOperate)
                {
                    this.btnAddArchiveBack.Visible = false;
                }
                if (!showReturn)
                    this.btnBack.Visible = false;
                this.attachArchive.ObjectID = ArchiveID;
                this.attachArchive.ObjectTableName = "";
                AddAttachmentInfos();
                InitControls();
                LoadData();
            }
        }

        /// <summary>
        /// 初始化数据项
        /// </summary>
        private void InitControls()
        {
            //保密期限
            DataSet keepSecurityTime = CodeTableService.GetCodeTableDataByType("KeepSecurityTime");
            if (keepSecurityTime != null && keepSecurityTime.Tables.Count > 0)
            {
                this.ddlKeepSecurityTime.DataSource = keepSecurityTime;
                this.ddlKeepSecurityTime.DataTextField = "Code_Desc";
                this.ddlKeepSecurityTime.DataValueField = "CodeTableID";
                this.ddlKeepSecurityTime.DataBind();
                this.ddlKeepSecurityTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            //初始化附件上传控件
            this.attachArchive.ObjectID = ArchiveID;
            DataSet KeepTime = CodeTableService.GetCodeTableDataByType("KeepTime");
            if (KeepTime != null && KeepTime.Tables.Count > 0)
            {
                this.ddlKeepTime.DataSource = KeepTime;
                this.ddlKeepTime.DataTextField = "Code_Desc";
                this.ddlKeepTime.DataValueField = "CodeTableID";
                this.ddlKeepTime.DataBind();
                this.ddlKeepTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            DataSet CarrierType = CodeTableService.GetCodeTableDataByType("CarrierType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlCarrierType.DataSource = CarrierType;
                this.ddlCarrierType.DataTextField = "Code_Desc";
                this.ddlCarrierType.DataValueField = "CodeTableID";
                this.ddlCarrierType.DataBind();
                this.ddlCarrierType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet SecurityData = CodeTableService.GetCodeTableDataByType("SecurityType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlSecurity.DataSource = SecurityData;
                this.ddlSecurity.DataTextField = "Code_Desc";
                this.ddlSecurity.DataValueField = "CodeTableID";
                this.ddlSecurity.DataBind();
                this.ddlSecurity.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu = ArchiveMenuService.GetArchiveMenuById(ReqArchiveType);
            if (dtArchiveMenu != null && dtArchiveMenu.Rows.Count > 0)
            {
                this.txtArchiveType.Text = (dtArchiveMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow).TYPECODE;
                this.archiveTypeName = (dtArchiveMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow).ARCHIVEMENU;
            }
            //来源
            this.txtArchiveSource.Text = "在线录入__档案整理";
            this.txtFileOrgName.Text = "厂中心档案室";
            this.txtBoxNum.Text = "未装盒";
            this.h_FileOrgID.Value = CommonUtil.GetConfigValue("ArchiveManage", "DefalutApproveOrgID");

            this.txtArchiveNum.Enabled = false;
            this.txtArchiveSource.Enabled = false;
            this.txtFullFondsNum.Enabled = false;
            this.txtArchiveType.Enabled = false;

            this.h_ArchiveTypeId.Value = ReqArchiveType;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            ICDArchiveService DocumentArchiveService = UContainer.Resolve<ICDArchiveService>();
            ArchiveMangeModal.CD_ARCHIVEDataTable dt = DocumentArchiveService.GetAllDocumenArchivetDataById(ArchiveID);
            if (dt.Rows.Count > 0)
            {
                this.CurrentPageState = PageState.State_Edit;

                ArchiveMangeModal.CD_ARCHIVERow row = dt.Rows[0] as ArchiveMangeModal.CD_ARCHIVERow;
                this.txtArchiveNum.Text = row.ARCHIVENUM;
                this.txtArchiveSource.Text = row.ARCHIVESOURCE;
                ArchiveMangeModal.ARCHIVEMENUDataTable dtMenu = ArchiveMenuService.GetArchiveMenuById(row.ARCHIVETYPE.ToString());
                ArchiveMangeModal.ARCHIVEMENURow drMenu = dtMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow;
                this.txtArchiveType.Text = drMenu.ARCHIVEMENU;
                this.h_ArchiveTypeId.Value = row.ARCHIVETYPE.ToString();
                this.txtBoxNum.Text = row.BOXNUM;
                //this.txtGloryType.Text = row.GLORYTYPE;
                //this.txtDoplicateBodyNum.Text = row.DOPLICATEBODYNUM.ToString();
                //this.txtFileNum.Text = row.FILENUM;
                //DataTable dtOrg = orgService.GetORGInfo(row.FILEORGID);
                //this.txtFileOrgName.Text = dtOrg.Rows[0]["Org_Name"].ToString();
                //this.h_FileOrgID.Value = row.FILEORGID;
                this.txtFileOrgName.Text = row.FILEORGID;
                this.txtFullFondsNum.Text = row.FULLFONDSNUM;
                this.txtMainBodyNum.Text = row.MAINBODYNUM.ToString();
                //this.txtPageNum.Text = row.PAGENUM.ToString();
                this.txtPublisher.Text = row.PUBLISHER;
                this.txtPublishTime.Text = row.PUBLISHTIME.ToString("yyyy-MM-dd");
                this.txtRemark.Text = row.REMARK;
                this.txtStorageType.Text = row.IsSTORAGETYPENull() ? string.Empty : row.STORAGETYPE;
                this.txtSummary.Text = row.SUMMARY;
                this.txtTempOrderNum.Text = row.TEMPORDERNUM;
                this.txtTitle.Text = row.TITLE;
                this.ddlCarrierType.SelectedValue = row.F_CARRIERTYPE;
                this.ddlKeepTime.SelectedValue = row.F_KEEPTIME;
                this.ddlSecurity.SelectedValue = row.F_SECURITYTYPE;
                this.txtHujianhao.Text = row.HUJIANHAO;
                this.ddlKeepSecurityTime.SelectedValue = row.F_KEEPSECURITYTIME;
            }
        }

        /// <summary>
        /// 附件实体增加更多信息
        /// </summary>
        private void AddAttachmentInfos()
        {
            Hashtable addInfos = new Hashtable();
            addInfos.Add("FunctionID", "0"); //功能ID(1：发文文档 2：发文附件 3：收文文档 4：收文附件 5：即时消息附件 6：新闻附件)
            addInfos.Add("FileTypeID", ""); //附件文件夹类型
            addInfos.Add("FileURL", ""); //附件存储路径
            addInfos.Add("IsXml", "0"); //是否XML代码化
            addInfos.Add("CreateUserID", this.CurrentUser.User_ID); //用户ID 目前可以写个固定的值作为测试
            addInfos.Add("Remark", "即时消息附件"); //备注
            if (Session["AddInfos"] == null)
            {
                Session.Add("AddInfos", addInfos);
            }
            else
            {
                Session.Remove("AddInfos");
                Session.Add("AddInfos", addInfos);
            }
        }
        #endregion

        #region 按钮事件


        /// <summary>
        /// 保存并返回按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddArchiveBack_Click(object sender, EventArgs e)
        {
            string errMsg = null;
            SaveData(ref errMsg);
            if (string.IsNullOrEmpty(errMsg))
            {
                Alert("保存成功！");
                if (!this.IsFromDataManage)
                {
                    GoBack();
                }
            }
            else
                Alert(errMsg);
        }

        /// <summary>
        /// 返回按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBack_Click(object sender, EventArgs e)
        {
            if (!this.IsFromDataManage)
            {
                GoBack();
            }
            else
            {
                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "window.close();", true);
            }
        }
        #endregion

        #region 页面方法
        private void SaveData(ref string errMsg)
        {
            ICDArchiveService DocumentArchiveService = UContainer.Resolve<ICDArchiveService>();
            if (string.IsNullOrEmpty(this.txtTitle.Text.Trim()))
            {
                errMsg = "标题不能为空!";
                return;
            }
            if (string.IsNullOrEmpty(this.txtPublisher.Text.Trim()))
            {
                errMsg = "责任人不能为空!";
                return;
            }
            DateTime o_time = new DateTime();
            if (string.IsNullOrEmpty(this.txtPublishTime.Text.Trim()) || !DateTime.TryParse(this.txtPublishTime.Text.Trim(), out o_time))
            {
                errMsg = "文件日期不能为空!";
                return;
            }
            int s_out = 0;
            
            if (!string.IsNullOrEmpty(this.txtMainBodyNum.Text.Trim()) && !int.TryParse(this.txtMainBodyNum.Text.Trim(), out s_out))
            {
                errMsg = "正文输入格式不正确!";
                return;
            }
            if (this.ddlCarrierType.SelectedIndex < 1)
            {
                errMsg = "载体类型不能为空!";
                return;
            }
            if (this.ddlKeepTime.SelectedIndex < 1)
            {
                errMsg = "保管期限不能为空!";
                return;
            }
            if (this.ddlSecurity.SelectedIndex < 1)
            {
                errMsg = "密级不能为空!";
                return;
            }
            else
            {
                //若有密级
                if (this.ddlSecurity.SelectedIndex != 1)
                {
                    if (this.ddlKeepSecurityTime.SelectedIndex < 1)
                    {
                        errMsg = "保密期限不能为空!";
                        return;
                    }
                }
            }
            ArchiveMangeModal.CD_ARCHIVEDataTable sourceTable = DocumentArchiveService.GetAllDocumenArchivetDataById(ArchiveID);
            ArchiveMangeModal.CD_ARCHIVERow sourceRow = sourceTable.Rows[0] as ArchiveMangeModal.CD_ARCHIVERow;

            DataSet ds = new DataSet();
            ArchiveMangeModal.CD_ARCHIVEDataTable dtDocumentArchive = new ArchiveMangeModal.CD_ARCHIVEDataTable();
            ArchiveMangeModal.CD_ARCHIVERow row = dtDocumentArchive.NewCD_ARCHIVERow();

            row.ItemArray = sourceRow.ItemArray;

            if (this.txtBoxNum.Text == "未装盒")
            {
                row.BOXNUM = null;
            }
            else
            {
                row.BOXNUM = this.txtBoxNum.Text;
            }


            row.LASTUPDATETIME = DateTime.Now;
            row.LASTUPDATEUSER = this.CurrentUser.User_ID;
            row.F_KEEPTIME = this.ddlKeepTime.SelectedValue;
            row.F_CARRIERTYPE = this.ddlCarrierType.SelectedValue;
            row.F_SECURITYTYPE = this.ddlSecurity.SelectedValue;
            row.F_KEEPSECURITYTIME = this.ddlKeepSecurityTime.SelectedValue;
            row.FILEORGID = this.txtFileOrgName.Text;
            row.FULLFONDSNUM = this.txtFullFondsNum.Text;

            int mainBodyNum;
            int.TryParse(this.txtMainBodyNum.Text.Trim(), out mainBodyNum);
            row.MAINBODYNUM = mainBodyNum;
            row.TITLE = this.txtTitle.Text;
            row.SUMMARY = this.txtSummary.Text;
            row.REMARK = this.txtRemark.Text;
            row.PUBLISHER = this.txtPublisher.Text;
            row.PUBLISHTIME = Convert.ToDateTime(this.txtPublishTime.Text);
            row.STORAGETYPE = this.txtStorageType.Text;
            row.TEMPORDERNUM = this.txtTempOrderNum.Text;
            row.HUJIANHAO = this.txtHujianhao.Text;
            dtDocumentArchive.NewRow();
            dtDocumentArchive.Rows.Add(row);

            dtDocumentArchive.AcceptChanges();
            row.SetModified();
            ds.Tables.Add(dtDocumentArchive);
            try
            {
                bool bResult = DocumentArchiveService.SaveData(ds);
                bResult = SaveAttachment() & bResult;
                WriteUserLog("用户" + CurrentUser.User_Name + "修改了光盘类的标题为" + row.TITLE + "的档案", OracleLogType.ArchiveManage);
            }
            catch (Exception ex)
            {
                errMsg = "保存失败,错误信息:" + ex.Message;
            }
        }

        private bool SaveAttachment()
        {
            DataTable dt_Attach = this.attachArchive.GetSaveDataTable(this.attachArchive.ObjectID, this.attachArchive.ObjectTableName);
            ICDArchiveService DocumentArchiveService = UContainer.Resolve<ICDArchiveService>();
            return DocumentArchiveService.SaveAttach(dt_Attach, this.attachArchive.ObjectTableName, this.attachArchive.ObjectID,
                 this.attachArchive.AttachmentDBHelperString);
        }

        
        #endregion
    }
}